/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.cam.ccn.sac.modules.audio;

import uk.ac.cam.ccn.sac.modules.audio.AudioThread;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

/**
 *
 * @author Thomas
 */
public class PlayThread extends AudioThread{
    private SourceDataLine line;
    private boolean isPlaying=true;
    private AudioInputStream ais;
    
    public PlayThread(byte[] record){
        super("PlayThread");
        try{        
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            line = (SourceDataLine)AudioSystem.getLine(info);
            InputStream input = new ByteArrayInputStream(record);
            ais = new AudioInputStream(input, format, record.length / format.getFrameSize());
        }catch(Exception e){
            System.out.println("Error opening line");
        }      
    }
    

    private boolean isStreaming=false;
    public PlayThread(InputStream input){
        super("PlayThread (stream)");
        try{        
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            line = (SourceDataLine)AudioSystem.getLine(info);
            ais = new AudioInputStream(input, format, 1000000);
            isStreaming=true;
        }catch(Exception e){
            System.out.println("Error opening line");
        }  
    }
    
    @Override
    public void run(){
        int bufferSize = (int)format.getSampleRate() * format.getFrameSize();
        byte buffer[] = new byte[bufferSize];
        int count;
        try{
            line.open(format);
            line.start();
            do{
                count = ais.read(buffer, 0, buffer.length);
                if(count > 0){
                    line.write(buffer, 0, count);
                }
            }while( isPlaying && (count!=-1 || isStreaming)); // we do not stop even if we do not read in stream mode
            System.out.println("Finish reading");
        }catch(Exception e){
            System.out.println(e.getMessage());
            System.out.println("Exception while playing");
        }finally{
            if(line!=null){
                line.drain();
                line.stop();
                line.close();
            }
        }
    }
    
    public void stopPlay(){
        isPlaying=false;
    }
}
